﻿using YMJake.Flowable.ExternalWorker.Client.AspNetCore.Pipeline;
using YMJake.Flowable.ExternalWorker.Client.Core.Client;

namespace YMJake.Flowable.ExternalWorker.Client.Sample.Handlers;

/// <summary>
/// 订单处理器 - 使用管道模式
/// </summary>
public class OrderProcessorHandler : IWorkerHandler
{
    private readonly ILogger<OrderProcessorHandler> _logger;

    public OrderProcessorHandler(ILogger<OrderProcessorHandler> logger)
    {
        _logger = logger;
    }

    public async Task HandleAsync(IWorkerPipelineContext context)
    {
        _logger.LogInformation("Processing order {OrderId}", context.Job.Id);

        try
        {
            // 获取订单数据
            var orderId = GetStringVariable(context.Job, "orderId", "unknown");
            var amount = Convert.ToDouble(context.Job.Variables.GetValueOrDefault("amount", 0));

            _logger.LogInformation("Processing order {OrderId} with amount {Amount}", orderId, amount);

            // 模拟处理
            await Task.Delay(1000, context.CancellationToken);

            // 设置成功结果
            context.Result = context.ResultBuilder.Success()
                .Variable("processedAt", DateTime.UtcNow)
                .Variable("status", "completed")
                .Variable("processedAmount", amount);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to process order {OrderId}", context.Job.Id);

            // 设置失败结果
            context.Result = context.ResultBuilder.Failure()
                .Error(ex)
                .WithRetries(3);
        }
    }

    private string GetStringVariable(IAcquiredExternalWorkerJob job, string key, string defaultValue = "")
    {
        var value = job.Variables.GetValueOrDefault(key, defaultValue);
        if (value == null) return defaultValue;
        
        var stringValue = value.ToString() ?? defaultValue;
        
        if (key == "data" || key == "message")
        {
            Console.WriteLine($"[DEBUG] {key} = '{stringValue}' (Length: {stringValue.Length})");
        }
            
        return stringValue;
    }
}